package com.izhengyin.miaosha.service.impl;

import com.izhengyin.miaosha.CreateOrderExecutor;
import com.izhengyin.miaosha.service.QueuingService;
import com.izhengyin.miaosha.service.TokenService;
import com.izhengyin.miaosha.service.external.InventoryService;
import com.izhengyin.miaosha.service.external.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@Slf4j
public class InProcessScheduleService {
    private final QueuingService queuingService;
    private final ItemService itemService;
    private final TokenService tokenService;
    private final InventoryService inventoryService;
    public InProcessScheduleService(QueuingService queuingService, ItemService itemService, TokenService tokenService, InventoryService inventoryService) {
        this.queuingService = queuingService;
        this.itemService = itemService;
        this.tokenService = tokenService;
        this.inventoryService = inventoryService;
    }

    /**
     * 本地调度器，进行调度
     */
    @Scheduled(fixedDelay = 1000,initialDelay = 1000)
    public void schedule(){
        List<Long> unfinishedItems = itemService.getUnfinishedItems();
        //都结束了
        if(unfinishedItems.isEmpty()){
            return;
        }
        //执行线程，空闲的队列大小
        int executorFreeQueueSize = CreateOrderExecutor.getMaxQueueSize() - CreateOrderExecutor.getExecutor().getQueue().size();
        int avgQueueSize = executorFreeQueueSize / unfinishedItems.size();
        for (Long itemId : unfinishedItems){
            //可用库存为0，结束秒杀
            if(inventoryService.getAvailableInventory(itemId) <= 0){
                itemService.setFinished(itemId);
                continue;
            }
            queuingService.dequeue(itemId,avgQueueSize)
                    .flatMap(tokenService::generate)
                    .doOnNext(token -> log.info("从队列中获取请求，生成 token {}",token))
                    .subscribe();
        }
    }
}
